import axios from 'axios';
import React from 'react';

class HttpClient {
  constructor() {
    this.instance = axios.create({
      baseURL: 'http://80.209.241.63:7001/v1', //process.env.REACT_APP_API_URL || 'http://80.209.241.49:7001/v1',
      timeout: 10000,
      headers: {
        'Content-Type': 'application/json'
      },
    });
    this.setupInterceptors();
  }

  setupInterceptors() {
    // 请求拦截器
    this.instance.interceptors.request.use(
      (config) => {
        const token = localStorage.getItem('token');
        if (token) {
          // config.headers.Authorization = `Bearer ${token}`;
          config.headers.token = `${token}`;
        }
        return config;
      },
      (error) => Promise.reject(error)
    );

    // 响应拦截器
    this.instance.interceptors.response.use(
      (response) => response.data,
      (error) => {
        this.handleError(error);
        return Promise.reject(error);
      }
    );
  }

  handleError(error) {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          localStorage.removeItem('token');
          window.location.href = 'Login';
          console.error('Unauthorized - Please login again');
          break;
        case 404:
          console.error('Resource not found');
          break;
        case 500:
          console.error('Server error');
          break;
        default:
          console.error('Request error:', error.message);
      }
    } else {
      console.error('Network error:', error.message);
    }
  }

  get(url, config = {}) {
    return this.instance.get(url, config);
  }

  post(url, data, config = {}) {
    return this.instance.post(url, data, config);
  }

  put(url, data, config = {}) {
    return this.instance.put(url, data, config);
  }

  delete(url, config = {}) {
    return this.instance.delete(url, config);
  }

  patch(url, data, config = {}) {
    return this.instance.patch(url, data, config);
  }
}

export const http = new HttpClient();